<?php

class Admin_AgendamentonapController extends App_Controller_Action
{

    private $_table     = 'AGENDA_ATENDIMENTONAP';
    private $_pk        = 'AGA_ID';
    private $_order_col = 'AGA_DAT DESC, AGA_HORINI';
    private $_order     = 'ASC';
    private $_sta_col   = 'AGA_STA';
    private $obj        = '';
    private $form       = '';
    private $_file_col  = 'AGA_FILE'; 
    public  $dir = 'public/upload//';
    public  $db = '';
    
    public function init()
    {
        if($this->getRequest()->getActionName() == 'edit') $this->form = new Admin_Form_Agendamentonap();        
    }

    public function indexAction() {
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        
        $where = ' WHERE '.$this->_pk . ' > 0 AND g.ALU_ID = a.ALU_ID';
        
        $filtro_nm = $this->_getParam('filtro_nm', '');
        $dtfiltro = $this->_getParam('dtfiltro', '');
        $dtfilfim = $this->_getParam('dtfilfim', '');
        
        if($filtro_nm != '') $where .= ' and a.ALU_NOM like "%' . trim($filtro_nm) .'%"';
        if($dtfiltro != '' && $dtfilfim == '') $where .= ' and g.AGA_DAT = "'.Datetools::dma_amd($dtfiltro).'"';
        else if($dtfilfim == '') $where .= ' and g.AGA_DAT >= "'.date('Y-m-d').'"';
        
        if($dtfiltro != '' && $dtfilfim != '') {
            $where .= ' and g.AGA_DAT >= "'.Datetools::dma_amd($dtfiltro).'"';
             $where .= ' and g.AGA_DAT <= "'.Datetools::dma_amd($dtfilfim).'"';
        }
        
        $this->view->filtro_nm = $filtro_nm;
        $this->view->dtfiltro = $dtfiltro;
        $this->view->dtfilfim = $dtfilfim;
        
        $query = 'SELECT SQL_CACHE g.*, a.ALU_NOM '
                .'FROM '.$this->_table.' g, ALUNO a '
                .$where.' ORDER BY g.'.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result);
        
    }
    
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_form_pdr.js');
       
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_agendamentonap.js?1='.rand(99,9999));
        
        Zend_Loader::loadClass('imagem','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        
        //$this->view->view = 'view';
        
        $this->view->form = $this->form;
        if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                if($this->form->isValid($formData)) {
                    
                    $id = (int) $this->form->getValue($this->_pk);
                    
                    $data = $this->form->getValues();
                    
                    unset($data['submit']);
                    unset($data['html']);
                    
                    $data['AGA_DAT'] = Datetools::dma_amd($data['AGA_DAT']);
   
                    $this->db->beginTransaction();
                    if($id == 0){
                        
                        $dia = Datetools::diasemanaData($data['AGA_DAT']);
                        
                        $query = 'SELECT SQL_CACHE  * FROM HORARIOS_AGENDAMENTONAP_HORA WHERE HAH_ID = '.$data['AGA_HORINI'].' AND HAH_DIASEM = '.$dia;
                        $row = $this->db->fetchRow($query);
                        
                        $data['AGA_HORINI'] = $row['HAH_HORINI'];
                        $data['AGA_HORFIM'] = $row['HAH_HORFIM'];
                        
                        $data[$this->_sta_col] = 1;
                        $this->db->insert($this->_table, $data);
                        $id =  $this->db->lastInsertId();   
                    }
                    else {
                        $data[$this->_sta_col] = $this->form->getValue($this->_sta_col,0);
                        $this->db->update($this->_table, $data,$this->_pk.' = ' . $id);
                    }
                    
                    $this->db->commit();
                    
                    $this->_helper->redirector('index');
                     
                } else {
                    $this->form->populate($formData);
                }
            } catch(Exception $ex) {
                //Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                $this->form->populate($formData);
                $this->db->rollBack();
            }
        } else {
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $data = $this->db->fetchRow('SELECT SQL_CACHE * FROM '.$this->_table.' WHERE '.$this->_pk . ' = ' . $id);
                $data['AGA_DAT'] = Datetools::amd_dma($data['AGA_DAT']);
                $this->form->populate($data);
            }else{
                $data['AGA_DAT'] = date('d/m/Y');
                $data['USU_ID'] = Zend_Auth::getInstance()->getStorage()->read()->USU_ID;
                $this->form->populate($data);
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $msg = '';
        $id = $this->_getParam('id', 0);
        if((int) $id > 0 ) {   
            $this->db->beginTransaction();
            try {
                
                $ok = (bool) $this->db->delete($this->_table, $this->_pk . ' = ' . $id);
                
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = MSG_DELETE;
                $this->db->rollBack();
            }             
        }       
        echo json_encode(array('ok' => $ok, 'msg'=> $msg));
        //$this->_helper->redirector('index');
    }
    
    public function buscahorariosAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = TRUE;
        $msg = '';
        $html = '<option value="">Nenhum</option>';
        $id = $this->_getParam('id', 0);
        $dat = $this->_getParam('dat', 1);
        
        Zend_Loader::loadClass('datetools','library');
        
        if($id > 0 && $dat > 0){
            
            $dia = Datetools::diasemanaData(Datetools::dma_amd($dat));
            
            $query = 'SELECT SQL_CACHE HAG_ID FROM HORARIOS_AGENDAMENTONAP WHERE USU_ID = '.$id;
            $row = $this->db->fetchRow($query);
            
            if($row['HAG_ID'] > 0){
            
                $query = 'SELECT SQL_CACHE  * FROM HORARIOS_AGENDAMENTONAP_HORA WHERE HAG_ID = '.$row['HAG_ID'].' AND HAH_DIASEM = '.$dia;
                $result = $this->db->fetchAll($query);
                foreach($result as $res) {
                    
                    $query = ' SELECT SQL_CACHE AGA_ID FROM AGENDA_ATENDIMENTONAP '
                            .' WHERE USU_ID = '.$id.' '
                            .' AND AGA_DAT = "'.Datetools::dma_amd($dat).'" '
                            .' AND AGA_HORINI >= "'.$res['HAH_HORINI'].'" '
                            .' AND AGA_HORFIM <= "'.$res['HAH_HORFIM'].'"';
                    $hor = $this->db->fetchRow($query);
                    
                    if(!isset($hor['AGA_ID'])){
                        $html .= '<option value="'.$res['HAH_ID'].'">'.Datetools::hora_hm($res['HAH_HORINI']).' às '.Datetools::hora_hm($res['HAH_HORFIM']).'</option>';   
                    }
                    
                }
            }
        }
       
        echo json_encode(array('ok' => $ok, 'html' => $html));
                
    }
    
}